package net.hmr_radio.hmrbot.service;

import javax.persistence.EntityExistsException;

import net.hmr_radio.hmrbot.model.Bot;
import net.hmr_radio.hmrbot.model.UserInfo;

import org.slim3.datastore.Datastore;

import twitter4j.Twitter;
import twitter4j.TwitterException;

import com.google.appengine.api.users.User;

public class UserInfoService {

    public UserInfo createNewUser(String userId) {
        UserInfo user = new UserInfo();
        user.setUserId(userId);
        user.setKey(user.createKey());

        if (Datastore.getOrNull(user.getKey()) != null) {
            throw new EntityExistsException("user["
                + userId
                + "] already exists");
        }

        Datastore.put(user);
        return user;
    }

    public UserInfo createNewUser(User googleAccount) {
        return createNewUser(googleAccount.getUserId());
    }

    public UserInfo createNewUser(Twitter twitter)
            throws IllegalStateException, TwitterException {
        return createNewUser(twitter.getScreenName());
    }

    public UserInfo get(String userId) {
        if (userId == null) {
            return null;
        }
        return Datastore.getOrNull(
            UserInfo.class,
            Datastore.createKey(UserInfo.class, userId));
    }

    public void save(UserInfo userInfo) {
        Datastore.put(userInfo);
    }

    public UserInfo get(User googleAccount) {
        return get(googleAccount.getUserId());
    }

    public UserInfo get(Bot bot) {
        return get(bot.getOwnerId());
    }

}
